package org.fjsei.yewu.job.controller;

import org.fjsei.yewu.job.controller.model.JobDetailModel;
import org.fjsei.yewu.job.controller.model.CreateJobDetailsRequestModel;
import org.fjsei.yewu.job.repository.SplJob;
import org.fjsei.yewu.job.service.QuartzJobManager;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.fjsei.yewu.job.service.SplitTask;
import org.quartz.JobDetail;
import org.quartz.SchedulerException;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/jobs")
@RequiredArgsConstructor
@Slf4j
@Validated
public class QuartzController {

    private final QuartzJobManager quartzJobManager;
    private final SplitTask splitTask;

    //Create or Update Job  没区分的 容易冲突
    @PostMapping("new")
    public ResponseEntity<String> createOrUpdateJob(@RequestBody @Valid CreateJobDetailsRequestModel createJobDetailsRequestModel) {
        try {
            quartzJobManager.createOrUpdateJob(createJobDetailsRequestModel);

            return ResponseEntity.ok().body("Job created/updated successfully");
        } catch (Exception exception) {
            log.error("Failed to create/update jobs. {}", exception.getMessage(), exception);
            return ResponseEntity.internalServerError().body("Failed to create/update jobs." + exception.getMessage());
        }
    }

    // Read Job  /。 / groupName 必须非汉字的的，# url失败
    @GetMapping("/{jobName}/{groupName}")
    public JobDetailModel getJobDetails(@PathVariable String jobName, @PathVariable String groupName) {
        try {
            JobDetail jobDetails = quartzJobManager.getJobDetails(jobName, groupName);
            return Optional.ofNullable(jobDetails)
                    .map(jobDetail -> JobDetailModel.builder().jobName(jobDetail.getKey().getName()).groupName(jobDetail.getKey().getGroup()).build()).orElseThrow(() -> new RuntimeException("No jobs found with jobName " + jobName));
        } catch (Exception exception) {
            log.error("Failed to get jobs with jobName {}. Error is {}", jobName, exception.getMessage(), exception);
            throw new RuntimeException("Failed to get jobs with jobName " + jobName);
        }
    }

    // Delete Job
    @DeleteMapping("/{jobName}/{groupName}")
    public String deleteJob(@PathVariable String jobName, @PathVariable String groupName) {
        try {
            boolean isDeleted = this.quartzJobManager.deleteJob(jobName, groupName);
            return isDeleted ? "Job deleted successfully: " + jobName : "Job not found:" + jobName;
        } catch (Exception exception) {
            log.error("Failed to delete jobs with jobName {}. Error is {}", jobName, exception.getMessage(), exception);
            return "Failed to delete jobs: " + exception.getMessage();
        }
    }


    // Pause Job 汉字不行 groupName
    @PostMapping(value = "/{jobName}/{groupName}/pause")
    public String pauseJob(@PathVariable String jobName, @PathVariable String groupName) {
        try {
            this.quartzJobManager.pauseJob(jobName, groupName);
            return "Job paused successfully: " + jobName;
        } catch (Exception exception) {
            log.error("Failed to pause jobs with jobName {}. Error is {}", jobName, exception.getMessage(), exception);
            return "Failed to pause jobs: " + exception.getMessage();
        }
    }
    //不能上     @PostMapping(value = "/{jobName}/{groupName}/run")
    // Resume Job
    @PostMapping(value = "/{jobName}/{groupName}/run")
    public String resumeJob(@PathVariable String jobName, @PathVariable String groupName) {
        try {
            this.quartzJobManager.resumeJob(jobName, groupName);
            return "Job resumed successfully: " + jobName;
        } catch (Exception exception) {
            log.error("Failed to resume jobs with jobName {}. Error is {}", jobName, exception.getMessage(), exception);
            return "Failed to resume jobs: " + exception.getMessage();
        }
    }

    //Read All Jobs
    @GetMapping
    public Set<JobDetailModel> getAllJobDetails() throws SchedulerException {
        return this.quartzJobManager.getAllJobDetails().stream()
                .map(jobDetail -> JobDetailModel.builder().jobName(jobDetail.getKey().getName()).groupName(jobDetail.getKey().getGroup()).build())
                .collect(Collectors.toSet());
    }
    @PostMapping(value = "/init/{jobName}/{groupName}")
    public String initJob(@PathVariable String jobName, @PathVariable String groupName) {
//        List<SplJob> batch=splitTask.trySplit(null);  //"infsyn-22", "groupName": "device",
        SplJob splJob=splitTask.commitSplit9("device", "infsyn-22");
        try {

            return "Job 拆分总数: " ;
        } catch (Exception exception) {
            log.error("Failed to resume jobs with jobName {}. Error is {}", jobName, exception.getMessage(), exception);
            return "Failed to resume jobs: " + exception.getMessage();
        }
    }
}